from urllib import request
import json



def sendMsg(token,msg):
    url = 'https://oapi.dingtalk.com/robot/send?access_token=' + token

    header = {'Content-Type': 'application/json; charset=utf-8'}


    req = request.Request(url, headers=header)
    res = request.urlopen(req, data=bytes(msg, encoding='utf-8'))
    print(res.read().decode())



# 普通文本消息
class TextMessage:
    def __init__(self):
        self.msgtype = 'text'
        self.text = {}

    def setText(self , text):
        self.text['content'] = text


class MarkdownMessage:
    def __init__(self):
        self.msgtype = 'markdown'
        self.markdown = {}

    def setTitle(self , title):
        self.markdown['title'] = title

    def setText(self , text):
        self.markdown['text'] = text

    def to_json_string(self):
        return json.dumps(self.__dict__ , ensure_ascii=False)


if __name__ == '__main__':
    m = TextMessage()
    m.setText('大家好啊\n时间：2018-12-12')

    d = MarkdownMessage()
    d.setTitle("消息提醒")
    d.setText("""# 过年消息提醒

好消息，好消息，**过年啦**,``back home``

- 放假
- 回家


上百度看一下 , [点我查看](http://www.baidu.com)""")

    str = json.dumps(d.__dict__ , ensure_ascii=False)
    sendMsg(str)